#pragma once
#include "../server.hpp"
#include <vector>
#include <string>
#include <cstdio>
#include <fstream>
#include <regex>

#include <cctype>

#include <sys/stat.h>

const int DEFAULT_TIMEOUT = 75;
std::unordered_map<int, std::string> _statu_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};


class Util
{
public:
    //将字符串src按照sep分隔符进行分割，结果存储在arry中
    static size_t Split(const std::string &src, const std::string &sep, std::vector<std::string> &arry)
    {
        std::string str;
        size_t len = src.size();
        size_t sep_len = sep.size();
        // 从src的pos位置开始匹配sep
        // 找到最后一个与sep匹配的位置
        auto get_pos = [&](int pos)
        {
            int i = 0;
            while (pos < len)
            {
                if (src[pos] == sep[i])
                {
                    ++pos;
                    ++i;
                }
                else
                    break;
            }
            return pos;
        };
        for (int i = 0; i < len; ++i)
        {
            if (src[i] == sep[0])
            {
                int pos = get_pos(i);
                // 如果pos-i等于sep的长度，说明找到了一个完整的分隔符
                if (pos - i == sep_len)
                {
                    if (!str.empty())
                        arry.push_back(str);
                    str.clear();
                }
                else
                {
                    str += src.substr(i, pos - i);
                }
                i = pos - 1; // 更新i的值，跳过已经处理的部分
                continue;
            }
            str += src[i];
        }
        if (!str.empty())
        {
            arry.push_back(str);
        }
        return arry.size();
    }

    //读取文件内容放入buffer中
    static bool ReadFile(const std::string& filename, std::string& buffer)
    {
        std::fstream fs(filename, std::fstream::in | std::fstream::binary);
        if (!fs.is_open())
        {
            ERROR_LOG("Failed to open file: %s", filename.c_str());
            return false;
        }
        fs.seekg(0, std::ios::end); // 移动到文件末尾
        size_t file_size = fs.tellg(); // 获取文件大小
        fs.seekg(0, std::ios::beg); // 移动到文件开头
        buffer.resize(file_size);
        fs.read(&buffer[0], file_size); // 读取文件内容到buffer中
        // 检查读取是否成功
        if(!fs.good())
        {
            ERROR_LOG("Failed to read file: %s", filename.c_str());
            fs.close();
            return false;
        }
        fs.close();
        return true;
    }


    static bool WriteFile(const std::string& filename, const std::string& buffer)
    {
        std::fstream fs(filename, std::fstream::out | std::fstream::binary | std::fstream::trunc);
        if (!fs.is_open())
        {
            ERROR_LOG("Failed to open file: %s", filename.c_str());
            return false;
        }
        fs << buffer;
        // 检查写入是否成功
        if(!fs.good())
        {
            ERROR_LOG("Failed to write file: %s", filename.c_str());
            fs.close();
            return false;
        }
        fs.close();
        return true;
    }

    //对URL进行编码
    //编码格式：将特殊字符的ascii值，转换为两个16进制字符，前缀%   C++ -> C%2B%2B
    //RFC3986文档规定 . - _ ~ 字母，数字属于绝对不编码字符
    //RFC3986文档规定，编码格式 %HH 
    //W3C标准中规定，查询字符串中的空格，需要编码为+， 解码则是+转空格
    static std::string UrlEncode(const std::string& url, bool convert_space_to_plus)
    {
        std::string encoded_url;
        for (int i = 0; i < url.size(); ++i)
        {
            char c = url[i];
            if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
            {
                encoded_url += c; // 直接添加不需要编码的字符
            }
            else if (c == ' ' && convert_space_to_plus)
            {
                encoded_url += '+'; // 空格转换为+
            }
            else
            {
                char buffer[4];
                snprintf(buffer, sizeof(buffer), "%%%02X", static_cast<unsigned char>(c)); // 编码为%HH格式
                encoded_url += buffer;
            }
        }
        return encoded_url;
    }


    static std::string UrlDecode(const std::string& url, bool convert_plus_to_space)
    {
        std::string decoded_url;
        for (size_t i = 0; i < url.size(); ++i)
        {
            char c = url[i];
            if (c == '%')
            {
                // 检查是否有足够的字符进行解码
                if (i + 2 < url.size() && isxdigit(url[i + 1]) && isxdigit(url[i + 2]))
                {
                    // 将%HH转换为对应的字符
                    std::string hex_str = url.substr(i + 1, 2);
                    char decoded_char = static_cast<char>(stol(hex_str, nullptr, 16));
                    decoded_url += decoded_char;
                    i += 2; // 跳过后面的两个字符
                }
                else
                {
                    // 如果格式不正确，直接返回空串
                    return "";
                }
            }
            else if (c == '+' && convert_plus_to_space)
            {
                decoded_url += ' '; // 将+转换为空格
            }
            else
            {
                decoded_url += c; // 直接添加其他字符
            }
        }
        return decoded_url;
    }


    //响应状态码的描述信息获取
    static std::string StatuDesc(int statu) {
        
        auto it = _statu_msg.find(statu);
        if (it != _statu_msg.end()) {
            return it->second;
        }
        return "Unknow";
    }


    //根据文件后缀名获取文件mime
    static std::string ExtMime(const std::string &filename) {
        
        // a.b.txt  先获取文件扩展名
        size_t pos = filename.find_last_of('.');
        if (pos == std::string::npos) {
            return "application/octet-stream";
        }
        //根据扩展名，获取mime
        std::string ext = filename.substr(pos);
        auto it = _mime_msg.find(ext);
        if (it == _mime_msg.end()) {
            return "application/octet-stream";
        }
        return it->second;
    }


    //判断是否是目录
    static bool IsDirectory(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;
        return S_ISDIR(st.st_mode);
    }


    //判断是否是普通文件
    static bool IsRegular(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if(ret < 0)
            return false;
        return S_ISREG(st.st_mode);
    }


    //请求路径的合法性判断
    //   /../index.html
    static bool ValidPath(const std::string& path)
    {
        std::vector<std::string> subdir;
        Split(path, "/", subdir);
        int level = 0;
        for(const auto& dir : subdir)
        {
            if (dir == "..")
            {
                --level;
                if (level < 0)
                    return false; // 不能上溯到根目录
            }
            ++level; // 正常目录
        }
        return true;
    }
};



//便于访问，成员变量设计为public
class HttpRequest
{
public:
    HttpRequest() 
        :_version("HTTP/1.1")
    {}


    void Reset()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch tmp;
        _matches.swap(tmp); // 清空_matches
        _headers.clear();
        _query_params.clear();
    }


    void SetHeader(const std::string& key, const std::string& value)
    {
        _headers[key] = value;
    }


    bool HasHeader(const std::string& key) const
    {
        return _headers.find(key) != _headers.end();
    }

    //获取请求头部的值
    const std::string& GetHeader(const std::string& key)const
    {
        auto it = _headers.find(key);
        if (it != _headers.end())
        {
            return it->second;
        }
        return "";
    }


    void SetParam(const std::string& key, const std::string& value) 
    {
        _query_params[key] = value;
    }


    bool HasParam(const std::string& key) const
    {
        return _query_params.find(key) != _query_params.end();
    }


    const std::string& GetParam(const std::string& key) const
    {
        auto it = _query_params.find(key);
        if (it != _query_params.end())
        {
            return it->second;
        }
        return "";
    }


    size_t ContentLength() const
    {
        const std::string& len = GetHeader("Content-Length");
        if(len == "")
            return 0;
        return std::stol(len);
    }


    bool IsKeepAlive() const
    {
        const std::string& connection = GetHeader("Connection");
        if(connection.empty())
        {
            // 如果没有指定Connection头部，HTTP/1.1默认是持久连接
            return _version == "HTTP/1.1";
        }
        if (connection == "keep-alive" || connection == "Keep-Alive")
        {
            return true;
        }
        // HTTP/1.1 默认是持久连接
        return false;
    }


public:
    std::string _method;
    std::string _path;
    std::string _version;
    std::string _body;
    std::smatch _matches;     //资源路径的正则提取数据
    std::unordered_map<std::string, std::string> _headers;
    std::unordered_map<std::string, std::string> _query_params; // 查询参数
};



class HttpResponse
{
public:
    HttpResponse(int status = 200)
        :_status(status)
        ,_redirect_flag(false)
        ,_version("HTTP/1.1")
    {}

    void Reset()
    {
        _status = 200;
        _redirect_flag = false;
        _redirect_url.clear();
        _headers.clear();
        _body.clear();
    }


    bool HasHeader(const std::string& key) const
    {
        return _headers.find(key) != _headers.end();
    }


    void SetHeader(const std::string& key, const std::string& value)
    {
        _headers[key] = value;
    }


    const std::string& GetHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if (it != _headers.end())
        {
            return it->second;
        }
        return "";
    }


    void SetContent(const std::string& body, const std::string& content_type = "text/html")
    {
        _body = body;
        SetHeader("Content-Type", content_type);
        SetHeader("Content-Length", std::to_string(body.size()));
    }


    void SetRiderectUrl(const std::string& url, int status= 302)
    {
        _status = status;
        _redirect_flag = true;
        _redirect_url = url;

    }

    bool IsKeepAlive() const
    {
        const std::string& connection = GetHeader("Connection");
        if(connection.empty())
        {
            // 如果没有指定Connection头部，HTTP/1.1默认是持久连接
            return _version == "HTTP/1.1";
        }
        if (connection == "keep-alive" || connection == "Keep-Alive")
        {
            return true;
        }
        // HTTP/1.1 默认是持久连接
        return false;
    }

public:
    int _status;
    bool _redirect_flag;
    std::string _redirect_url;
    std::string _version;
    std::unordered_map<std::string, std::string> _headers;
    std::string _body;
};


typedef enum
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEADER,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
} HttpRecvStatu;


const int MAX_LINE = 8192;


class HttpContext
{
public:
    HttpContext()
        :_resp_statu(200)
        ,_recv_statu(RECV_HTTP_LINE)
    {}

    void Reset()
    {
        _request.Reset();
        _recv_statu = RECV_HTTP_LINE;
        _resp_statu = 200;
    }

    int RespStatu() const
    {
        return _resp_statu;
    }


    HttpRecvStatu RecvStatu() 
    { 
        return _recv_statu; 
    }


    HttpRequest &Request() 
    { 
        return _request; 
    }


    
    void RecvAndParseHttpRequest(Buffer &buf)
    {
        //处理完当前状态后，接着处理下一个状态
        switch(_recv_statu)
        {
            case RECV_HTTP_LINE:
                RecvHttpLine(buf);
            case RECV_HTTP_HEADER:
                RecvHttpHeader(buf);
            case RECV_HTTP_BODY:
                RecvBody(buf);
        }
    }


private:
    bool RecvHttpLine(Buffer& buffer)
    {
        if (_recv_statu != RECV_HTTP_LINE) 
            return false;

        std::string buf = std::move(buffer.GetLineAndPop());
        if(buf.empty())
        {
            int sz = buffer.EffectiveDataSize();
            if(sz > MAX_LINE)
            {
                ERROR_LOG("HTTP line too long, size: %d", sz);
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;
                return false;
            }
            return true;
        }
        if(buf.size() > MAX_LINE)
        {
            ERROR_LOG("HTTP line too long, size: %d", buf.size());
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 414;
            return false;
        }
        bool ret = ParseHttpLine(buf);
        if(!ret)
        {
            return false;
        }
        _recv_statu = RECV_HTTP_HEADER;
        return true;
    }


    bool ParseHttpLine(const std::string& line)
    {
        // GET /example/path/to/resource?param=1 HTTP/1.0
        // [1] GET
        // [2]: /example/path/to/resource
        // [3]: param=1 (无查询参数也会占位)
        // [4]: HTTP/1.0
        // ^?表示匹配除了?之外的字符
        // []中的字符通常不用转义
        // (?:\\?(.*))? 表示可选的查询参数部分，(?:...)是非捕获组
        // 非捕获组是指不需要单独捕获的组，(?:...)不会在结果中返回
        // 这里表示?不单独返回
        // ?表示匹配0次或1次
        std::regex pattern ("(GET|POST|DELETE|PUT|HEAD) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[10])(?:\n|\r\n)?", std::regex::icase);
        std::smatch match;
        bool ret = std::regex_match(line, match, pattern);
        if (!ret)
        {
            ERROR_LOG("HTTP line parse error: %s", line.c_str());
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400; // Bad Request
            return false;
        }
        _request._method = match[1].str();
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        // 需要解码
        _request._path = Util::UrlDecode(match[2].str(), false);
        _request._version = match[4].str();

        //需要解码
        //解析查询参数
        const std::string& query_str = match[3].str();
        if (query_str.empty())
        {
            return true;
        }
        std::string query_str_decoded = Util::UrlDecode(query_str, true);
        std::vector<std::string> query_params;
        Util::Split(query_str_decoded, "&", query_params); 
        for (const auto& param : query_params)
        {
            size_t pos = param.find('=');
            if(pos == std::string::npos)
            {
                ERROR_LOG("Invalid query parameter: %s", param.c_str());
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 400; // Bad Request
                return false;
            }
            const auto& key = param.substr(0, pos);
            const auto& value = param.substr(pos + 1);
            _request.SetParam(key, value);
        }
        return true;
    }


    bool RecvHttpHeader(Buffer& buffer)
    {
        if(_recv_statu != RECV_HTTP_HEADER)
            return false;
        std::string buf = std::move(buffer.GetLineAndPop());
        while(buf != "\r\n" && buf != "\n" && buffer.EffectiveDataSize() > 0)
        {
            if(buf.empty())
            {
                int sz = buffer.EffectiveDataSize();
                if(sz > MAX_LINE)
                {
                    ERROR_LOG("HTTP line too long, size: %d", sz);
                    _recv_statu = RECV_HTTP_ERROR;
                    _resp_statu = 414;
                    return false;
                }
                return true;
            }
            if(buf.size() > MAX_LINE)
            {
                ERROR_LOG("HTTP line too long, size: %d", buf.size());
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;
                return false;
            }
            bool ret = ParseHttpHeader(buf);
            if(!ret)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;
                return false;
            }
            buf = std::move(buffer.GetLineAndPop());
        }
        _recv_statu = RECV_HTTP_BODY;
        return true;
    }


    bool ParseHttpHeader(std::string& line)
    {
        if(line.back() == '\n')
            line.pop_back(); // 去掉末尾的换行符
        if(line.back() == '\r')
            line.pop_back(); // 去掉末尾的回车符
        int pos = line.find(':');
        if(pos == std::string::npos)
        {
            ERROR_LOG("HTTP header parse error: %s", line.c_str());
            return false;
        }
        const std::string& key = line.substr(0, pos);
        const std::string& value = line.substr(pos + 2);
        _request.SetHeader(key, value);
        return true;
    }


    bool RecvBody(Buffer& buffer)
    {
        if(_recv_statu != RECV_HTTP_BODY)
            return false;
        size_t content_length = _request.ContentLength();
        if(content_length == 0)
        {
            _recv_statu = RECV_HTTP_OVER;
            return true; // 没有请求体，直接结束
        }

        size_t real_size = content_length - _request._body.size();
        if(real_size > buffer.EffectiveDataSize())
        {
            _request._body += std::move(buffer.ReadStringAndPop(buffer.EffectiveDataSize()));
        }
        else
        {
            _request._body += std::move(buffer.ReadStringAndPop(real_size));
            _recv_statu = RECV_HTTP_OVER; // 请求体接收完毕
        }
        return true;
    }
private:
    //响应状态码
    int _resp_statu;
    //当前已经接收的状态
    HttpRecvStatu _recv_statu;          
    //当前已经解析的请求信息
    HttpRequest _request; 
    
};


class HttpServer
{
private:
    using Handler = std::function<void(const HttpRequest&, HttpResponse&)>;
    using Handlers = std::vector<std::pair<std::regex, Handler>>;
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    std::string _basedir;
    TcpServer _server;
private:
    void ErrorHandler(const HttpRequest &req, HttpResponse &rsp)
    {
        //1. 组织一个错误展示页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(rsp._status);
        body += " ";
        body += Util::StatuDesc(rsp._status);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        //2. 将页面数据，当作响应正文，放入rsp中
        rsp.SetContent(body, "text/html");

    }

    void WriteResponse(const PtrConnection &conn, const HttpRequest &req, HttpResponse &rsp)
    {
        //完善头部字段
        if(req.IsKeepAlive())
        {
            rsp.SetHeader("Connection", "keep-alive");
        }
        else
        {
            rsp.SetHeader("Connection", "close");
        }
        if(!rsp._body.empty())
        {
            if(!rsp.HasHeader("Content-Length"))
            {
                rsp.SetHeader("Content-Length", std::to_string(rsp._body.size()));
            }
            if(!rsp.HasHeader("Content-Type"))
            {
                rsp.SetHeader("Content-Type", "application/octet-stream");
            }
        }
        if(rsp._redirect_flag)
        {
            rsp.SetHeader("Location", rsp._redirect_url);
        }
        //按照http格式组织
        std::stringstream rsp_str;
        rsp_str << req._version << ' ' << rsp._status << ' ' << Util::StatuDesc(rsp._status) << "\r\n";
        for (auto& header : rsp._headers)
        {
            rsp_str << header.first << ": " << header.second << "\r\n";
        }
        rsp_str << "\r\n" << rsp._body;

        //发送响应
        conn->Send(rsp_str.str().c_str(), rsp_str.str().size());
    }
    


    void FileHandler(HttpRequest& req, HttpResponse& rsp)
    {
        std::string req_path = _basedir + req._path;
        if(req_path.back() == '/')
        {
            // 如果请求路径是目录，默认访问index.html
            req_path += "index.html";
        }
        bool ret = Util::ReadFile(req_path, rsp._body);
        if(!ret)
        {
            return;
        }
        std::string mime = std::move(Util::ExtMime(req_path));
        rsp.SetHeader("Content-Type", mime);
    }



    bool IsFileHandler(HttpRequest& req)
    {
        if(_basedir.empty())
            return false;
        if(req._method != "GET" && req._method != "HEAD")
            return false;
        if(!Util::ValidPath(req._path))
            return false;
        std::string req_path = _basedir + req._path;
        if(req_path.back() == '/')
        {
            // 如果请求路径是目录，默认访问index.html
            req_path += "index.html";
        }
        if(!Util::IsRegular(req_path))
        {
            return false;
        }
        return true;
    }


    void Dispatcher(HttpRequest& req, HttpResponse& rsp, Handlers& handlers)
    {
        for(auto& handler : handlers)
        {
            std::regex& pattern = handler.first;
            auto& func = handler.second;
            std::smatch match;
            if(!std::regex_match(req._path, match, pattern))
                continue;
            func(req, rsp);
            return;
        }
        rsp._status = 404;
    }



    void Route(HttpRequest& req, HttpResponse& rsp)
    {
        if(IsFileHandler(req))
        {
            FileHandler(req, rsp);
            return;
        }
        if(req._method == "GET" || req._method == "HEAD")
        {
            Dispatcher(req, rsp, _get_route);
            return;
        }
        else if(req._method == "POST")
        {
            Dispatcher(req, rsp, _post_route);
            return;
        }
        else if(req._method == "PUT")
        {
            Dispatcher(req, rsp, _put_route);
            return;
        }
        else if(req._method == "DELETE")
        {
            Dispatcher(req, rsp, _delete_route);
            return;
        }
        rsp._status = 405; // Method Not Allowed
        return;
    }

    //设置上下文
    void OnConnected(const PtrConnection &conn) 
    {
        conn->SetContext(HttpContext());
        DEBUG_LOG("NEW CONNECTION %p", conn.get());
    }

    void OnMessage(const PtrConnection& conn, Buffer& buffer)
    {
        while(buffer.EffectiveDataSize() > 0)
        {
            HttpContext* context = conn->GetContext()->get<HttpContext>();
            if(!context)
            {
                ERROR_LOG("HttpContext not found in connection context");
                return;
            }
            context->RecvAndParseHttpRequest(buffer);
            HttpRequest &req = context->Request();
            HttpResponse rsp(context->RespStatu());

            if(context->RecvStatu() == RECV_HTTP_ERROR || context->RespStatu() >= 400)
            {
                //组织错误页面
                ErrorHandler(req, rsp);
                //发送响应
                WriteResponse(conn, req, rsp);
                context->Reset();
                buffer.MoveReadOffset(buffer.EffectiveDataSize()); // 清空已处理的数据
                conn->Shutdown();
                return;
            }
            if(context->RecvStatu() != RECV_HTTP_OVER)
            {
                // 还没有接收完请求，等待下一次消息
                return;
            }
            Route(req, rsp);
            WriteResponse(conn, req, rsp);
            context->Reset();
            if(!context->Request().IsKeepAlive())
            {
                conn->Shutdown(); // 如果不是持久连接，关闭连接
                //return;??
            }

        }
    }
public:
    HttpServer(uint16_t port, int timeout = DEFAULT_TIMEOUT)
        :_server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));

    }


    void SetBaseDir(const std::string &path) 
    {
        assert(Util::IsDirectory(path) == true);
        _basedir = path;
    }
    /*设置/添加，请求（请求的正则表达）与处理函数的映射关系*/
    void Get(const std::string &pattern, const Handler &handler) 
    {
        _get_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Post(const std::string &pattern, const Handler &handler) 
    {
        _post_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Put(const std::string &pattern, const Handler &handler) 
    {
        _put_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Delete(const std::string &pattern, const Handler &handler) 
    {
        _delete_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void SetThreadCount(int count) 
    {
        _server.SetThreadsNum(count);
    }
    void Listen() 
    {
        _server.Start();
    }

};


